/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelCancelamentoEntrada.java
 *
 * Created on 02/10/2011, 18:54:58
 */

package modules.enderecamento.gui.jpanel;

import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.swing.Box;
import javax.swing.JFormattedTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import modules.enderecamento.facade.WMSFacade;
import modules.enderecamento.models.dto.Entrada;
import modules.enderecamento.util.BoxPanel;
import modules.enderecamento.util.Funcoes;
import modules.enderecamento.validation.Validation;

/**
 *
 * @author Clezio
 */
public class PanelCancelamentoEntrada extends javax.swing.JPanel {

    MaskFormatter formatoData;
    private WMSFacade wmsFacade;
    /** Creates new form PanelCancelamentoEntrada */
    public PanelCancelamentoEntrada() {
        try {
            formatoData = new MaskFormatter("##/##/####");
        } catch (Exception erro) {}
        initComponents();
        wmsFacade = new WMSFacade();

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(44);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(143);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(52);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(55);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(146);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(210);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(52);
        jTable1.getColumnModel().getColumn(7).setPreferredWidth(75);

        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        wMSLabel1 = new modules.enderecamento.gui.custom.WMSLabel();
        tfData = new JFormattedTextField(formatoData);
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.enderecamento.gui.custom.WMSJTable();
        btnObterRegistros = new modules.enderecamento.gui.custom.WMSJButton();
        btnCancelar = new modules.enderecamento.gui.custom.WMSJButton();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Cancelamento de registro de entrada");

        wMSLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel1.setText("Data:");

        tfData.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        tfData.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfDataKeyPressed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Natureza", "Rua", "Palete", "Código", "Descrição", "Qtde", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnObterRegistros.setMnemonic('C');
        btnObterRegistros.setText("Consultar");
        btnObterRegistros.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnObterRegistrosActionPerformed(evt);
            }
        });

        btnCancelar.setMnemonic('a');
        btnCancelar.setText("Cancelar registro");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(135, 135, 135)
                        .addComponent(tfData, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnObterRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(339, 339, 339)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(23, 23, 23)
                            .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 780, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(10, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(115, 115, 115)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnObterRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(65, 65, 65)
                    .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(390, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfDataKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDataKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            obterRegistros();
        }
}//GEN-LAST:event_tfDataKeyPressed

    private void btnObterRegistrosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnObterRegistrosActionPerformed
        obterRegistros();
    }//GEN-LAST:event_btnObterRegistrosActionPerformed

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
//        tfData.setText(Funcoes.dateToString(new Date()));
        tfData.requestFocus();
    }//GEN-LAST:event_formAncestorAdded

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

    }//GEN-LAST:event_jTable1MouseClicked

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        efetuarCancelamento();
    }//GEN-LAST:event_btnCancelarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.enderecamento.gui.custom.WMSJButton btnCancelar;
    private modules.enderecamento.gui.custom.WMSJButton btnObterRegistros;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private modules.enderecamento.gui.custom.WMSJTable jTable1;
    private javax.swing.JTextField tfData;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel1;
    // End of variables declaration//GEN-END:variables

    private void efetuarCancelamento() {
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int[] selected = jTable1.getSelectedRows();
            int id = (Integer) modelo.getValueAt(selected[0], 0);
            Entrada entrada = wmsFacade.obterEntradaById(id);
            if(entrada != null){
                wmsFacade.cancelarEntrada(entrada);
            }
            obterRegistros();
        } else {
            BoxPanel.showMessageDialog(null, "Selecione um registro para cancelar.");
        }
    }

    private void obterRegistros() {
        Date date = null;
        try {
            date = Funcoes.stringToDate(tfData.getText());
            if(date.after(new Date())){
                Validation.getInstance().addErros("data", "A data não pode ser superior a data atual.");
            }
        } catch (ParseException ex) {
            if(tfData.getText().equals("  /  /    ")){
                Validation.getInstance().addErros("data", "Data é um campo obrigatório.");
            }else{
                Validation.getInstance().addErros("data", "A data informada inválida.");
            }
        }
        if(Validation.getInstance().hasErrors()){
            BoxPanel.showMessageError(Funcoes.getListErros(Validation.getInstance().getErros()));
            return;
        }
        listarRegistro(wmsFacade.listarEntradasByData(date));
    }

    private void listarRegistro(List<Entrada> registros) {
        if(registros != null){
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            modelo.setNumRows(0);
            if(registros.isEmpty()){
                BoxPanel.showMessageDialog(null, "Não foram encontrados nenhum registro com o parâmetro passado.");
                return;
            }
            for (int i = 0; i < registros.size(); i++) {
                int id = registros.get(i).getId();
                String rua = registros.get(i).getRua().getNome();
                Integer palete = registros.get(i).getPalete().getId();
                String codigo = registros.get(i).getProduto().getCodigo();
                String descricao = registros.get(i).getProduto().getDescricao();
                Integer quantidade = registros.get(i).getQuantidade();
                String natureza = registros.get(i).getTiposMovimento().getNome();
                String status = "Ok";
                if (registros.get(i).isCancelado()) {
                    status = "Cancelado";
                }
                modelo.addRow(new Object[]{
                            id,natureza, rua, palete,codigo,descricao,quantidade,status
                        });
            }
        }
    }

}
